package com.yellow.userservice.service.LoginServiceImpl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.yellow.userservice.config.SmsConfig;
import com.yellow.userservice.service.LoginService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author: hy
 * @create: 2024-03-23
 */
@Slf4j
@Service
public class CodeLoginService implements LoginService {
   @Resource
   private SmsConfig smsConfig;


    @Override
    public boolean login(String phoneNumber, String code) {

        try {
            sendSms(phoneNumber,code);
        }
        catch (Exception e){
            log.info("发送短信验证码出错");
            e.printStackTrace();
        }
        System.out.println("Executing code userservice for user: " + phoneNumber);

        return true;
    }

    public void sendSms(String phoneNumber, String code) throws ClientException {
        // 创建DefaultAcsClient实例并初始化
        DefaultProfile profile = DefaultProfile.getProfile(
                "default", // 地域ID
                smsConfig.getAccessKeyId(),
                smsConfig.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);

        // 创建API请求并设置参数
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phoneNumber);
        request.setSignName(smsConfig.getSignName());
        request.setTemplateCode(smsConfig.getTemplateCode());
        request.setTemplateParam("{\"code\":\"" + code + "\"}"); // 假设模板中有变量${code}

        // 发送短信并处理响应
        SendSmsResponse response = client.getAcsResponse(request);
        System.out.println(response);
        if (!"OK".equals(response.getCode())) {
            throw new ClientException("短信发送失败，原因：" + response.getMessage());
        }

    }
}
